package com.mediacloud.app.newsmodule.fragment.video.vod

import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.mediacloud.app.assembly.util.isFastClick
import com.mediacloud.app.fbnavsk.navPaddingTopMatch
import com.mediacloud.app.model.interfaces.DataInvokeCallBack
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.ArticleListData
import com.mediacloud.app.model.news.BaseMessageReciver
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.utils.LogUtil
import com.mediacloud.app.model.utils.ViewUtils
import com.mediacloud.app.model.view.floatwin.FloatButtonGroup
import com.mediacloud.app.nav2.fragment.HqyNavFragment
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.activity.microlive.BaseRecyclerAdapter
import com.mediacloud.app.newsmodule.fragment.baoliao.api.SpiderCmsApi
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils
import com.mediacloud.app.newsmodule.utils.NewsListDataInvoker
import com.mediacloud.app.reslib.enums.ToolBarActionF5OrTop
import com.mediacloud.app.reslib.util.ModuleReferenceConfig
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.movie_fragment.*
import org.jetbrains.anko.backgroundResource
import org.jetbrains.anko.textColor
import org.json.JSONObject

/**
Date:2021/6/9
剧集导航
Author:Wy
 */
class MovieFragment : HqyNavFragment(), BaseRecyclerAdapter.ItemClickListener,
    ToolBarActionF5OrTop {

    var dataInvoker: NewsListDataInvoker? = null
    var dataCallback: BaseDataInvokeCallBack<out BaseMessageReciver?>? = null

    val LOGIN = 1
    val REFRESH = 2
    var Mode = REFRESH

    var catalogItem: CatalogItem? = null
    var catalogID: String? = null
    var pageIndex = 1
    var perPageSize = 20
    lateinit var movieGridAdapter: MovieListAdapter
    lateinit var countryAdapter: CategoryAdapter
    lateinit var typeAdapter: CategoryAdapter
    lateinit var yearAdapter: CategoryAdapter
    private var chooseType: Boolean = false

    override fun getLayoutResID(): Int {
        return R.layout.movie_fragment
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        this.navPaddingTopMatch()
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun initView() {
        layout_search.setOnClickListener {
            if (isFastClick()){
                val intent = Intent()
                intent.setClassName(requireContext(), ModuleReferenceConfig.SearchActivity)
                startActivity(intent)
            }

        }
        refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                refresh()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {

                loadMore()
            }
        })
        val layoutManager = GridLayoutManager(activity, 3)
        layoutManager.orientation = LinearLayoutManager.VERTICAL
        recyclerView.layoutManager = layoutManager
        recyclerView.setBackgroundColor(Color.WHITE)
        movieGridAdapter = MovieListAdapter(activity)
        movieGridAdapter.setItemClickListener(this)
        recyclerView.adapter = movieGridAdapter
        loadingView = mRootView.findViewById(R.id.mLoadingView)
        loadingImage = loadingView.findViewById(R.id.image_loading)
        retryTips = loadingView.findViewById(R.id.retryTips)

        if(retryTips!=null){
            retryTips.setOnClickListener {
                showStateView(TYPE_LOADING, false)
                refresh()
            }
        }

        country_content.layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
        countryAdapter = CategoryAdapter(R.layout.category_item)
        country_content.adapter = countryAdapter
        type_content.layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
        typeAdapter = CategoryAdapter(R.layout.category_item)
        type_content.adapter = typeAdapter
        year_content.layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
        yearAdapter = CategoryAdapter(R.layout.category_item)
        year_content.adapter = yearAdapter

        refresh()
        getCategoryData()
    }

    override fun initArgs() {
        super.initArgs()
        if (fragmentArguments != null) {
            saveInstanceArguments = fragmentArguments
            catalogID = saveInstanceArguments?.getString("id")
            catalogItem = saveInstanceArguments?.getParcelable("catalog")
        } else if (saveInstanceArguments != null) {
            catalogID = saveInstanceArguments?.getString("id")
            catalogItem = saveInstanceArguments?.getParcelable("catalog")
        }
        val navigateArgs = if (catalogItem != null && catalogItem?.navigate != null) {
            catalogItem?.navigate
        } else {
            super.navigate
        }
        navigate = navigateArgs
        initCallBackInstance()
        initDataInvoker()
    }

    private fun getCategoryData() {
        var programId = -1
        navigate?.categoryChildren?.forEach {
            if (it.name == catalogItem?.catname) {
                programId = it.programid
            }
        }
        val map = mutableMapOf<String, Any>()
        if (programId != -1) {
            map["programId"] = programId
        }
        SpiderCmsApi.getSpiderCmsApi(requireContext())
                .getCategory(getString(R.string.tenantid), map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<CategoryData> {
                    override fun onSubscribe(d: Disposable) {
                        compositeDisposable.add(d)
                    }

                    override fun onNext(t: CategoryData) {
                        if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                            return
                        }
                        if (t.isSuccess) {
                            countryAdapter.data.addAll(t.data.country)
                            typeAdapter.data.addAll(t.data.type)
                            yearAdapter.data.addAll(t.data.year)
                            yearAdapter.data.reverse()
                            countryAdapter.data.add(0, "全部")
                            typeAdapter.data.add(0, "全部")
                            yearAdapter.data.add(0, "全部")
                            countryAdapter.notifyItemRangeChanged(0, t.data.country.size)
                            typeAdapter.notifyItemRangeChanged(0, t.data.type.size)
                            yearAdapter.notifyItemRangeChanged(0, t.data.year.size)
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                            return
                        }
                        Log.e(TAG, "${e.message}")
                    }

                    override fun onComplete() {}
                })
    }

    private fun getDramaData() {
        loadingView.setBackgroundColor(Color.TRANSPARENT)
        showStateView(TYPE_LOADING, false)
        val countryIndex = countryAdapter.choosePosition
        val typeIndex = typeAdapter.choosePosition
        val yearIndex = yearAdapter.choosePosition
        var country: Any = ""
        var type: Any = ""
        var year: Any = ""
        if (countryIndex != 0) {
            country = countryAdapter.data[countryIndex]
        }
        if (typeIndex != 0) {
            type = typeAdapter.data[typeIndex]
        }
        if (yearIndex != 0) {
            year = yearAdapter.data[yearIndex]
        }
        val map = mutableMapOf<String, Any>()
        if (country.toString().isNotEmpty()) {
            map["country"] = country
        }
        if (type.toString().isNotEmpty()) {
            map["seriesType"] = type
        }
        if (year.toString().isNotEmpty()) {
            map["year"] = year
        }
        map["pageNumber"] = pageIndex
        map["pageSize"] = perPageSize
        var catId = ""
        navigate?.categoryChildren?.forEach {
            if (it.name == catalogItem?.catname) {
                catId = it.catid
            }
        }
        map["catalogIds"] = catId
        SpiderCmsApi.getSpiderCmsApiJson(requireContext())
                .findSeriesPageForApp(getString(R.string.tenantid), map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<JSONObject> {
                    override fun onSubscribe(d: Disposable) {
                        compositeDisposable.add(d)
                    }

                    override fun onNext(t: JSONObject) {
                        if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                            return
                        }
                        refreshLayout.finishRefresh()
                        refreshLayout.finishLoadMore()
                        closeStateView()
                        val success = t.optBoolean("success")
                        if (success) {
                            val json = t.optJSONObject("data")
                            if (json != null) {
                                val hasNextPage = json.optBoolean("hasNextPage")
                                if (!hasNextPage) {
                                    refreshLayout.setNoMoreData(true)
                                }
                                if (pageIndex == 1) {
                                    movieGridAdapter.data.clear()
                                }
                                val meta = json.optJSONArray("pageRecords")
                                if (meta != null && meta.length() > 0) {
                                    val list = arrayListOf<ArticleItem>()
                                    for (i in 0 until meta.length()) {
                                        val item = meta.optJSONObject(i)
                                        val articleItem = ArticleItem()
                                        articleItem.id = item.optLong("id")
                                        articleItem.logo = item.optString("logo")
                                        articleItem.title = item.optString("title")
                                        articleItem.type = item.optString("type").toInt()
                                        articleItem.url = item.optString("url")
                                        articleItem.appCustomParams = item.optJSONObject("appCustomParams")?.toString()
                                            ?: ""
                                        articleItem.author = item.optString("author")
                                        articleItem.Author = item.optString("Author")
                                        articleItem.favorCount_format = item.optInt("favorCount").toString()
                                        articleItem.commentCount = item.optLong("commentCount")
                                        articleItem.commentCount_format = item.optInt("commentCount").toString()
                                        articleItem.catalogId = item.optInt("catalogId")
                                        list.add(articleItem)
                                    }
                                    empty_content.visibility = View.GONE
                                    recyclerView.visibility = View.VISIBLE
                                    movieGridAdapter.data.addAll(list)
                                } else {
                                    movieGridAdapter.data.addAll(emptyList())
                                    empty_content.visibility = View.VISIBLE
                                    recyclerView.visibility = View.GONE
                                }
                            } else {
                                movieGridAdapter.data.addAll(emptyList())
                                empty_content.visibility = View.VISIBLE
                                recyclerView.visibility = View.GONE
                            }
                        } else {
                            movieGridAdapter.data.addAll(emptyList())
                            empty_content.visibility = View.VISIBLE
                            recyclerView.visibility = View.GONE
                        }
                        movieGridAdapter.notifyDataSetChanged()
                    }

                    override fun onError(e: Throwable) {
                        if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                            return
                        }
                        Log.e(TAG, "${e.message}")
                        refreshLayout.finishRefresh()
                        refreshLayout.finishLoadMore()
                        closeStateView()
                        empty_content.visibility = View.VISIBLE
                        recyclerView.visibility = View.GONE
                    }

                    override fun onComplete() {}
                })
    }

    private fun refresh() {
        pageIndex = 1
        if (chooseType) {
            getDramaData()
        } else {
            load()
        }
    }

    private fun loadMore() {
        pageIndex++
        if (chooseType) {
            getDramaData()
        } else {
            load()
        }
    }

    private fun load() {
        Mode = REFRESH
        dataInvoker?.getContentListWithAd(catalogID, pageIndex, perPageSize,null)
    }


    private fun initDataInvoker() {
        dataInvoker = NewsListDataInvoker(dataCallback)
    }


    protected fun getDataInvokeCallBackClass(): Class<out BaseDataInvokeCallBack<out BaseMessageReciver?>?> {
        return BaseNewsDataInvokeCallBack::class.java
    }


    private fun initCallBackInstance() {
//        val classRef: Class<*> = getDataInvokeCallBackClass()
        try {
//            dataCallback = classRef.constructors[0].newInstance(this) as BaseDataInvokeCallBack<out BaseMessageReciver?>
            dataCallback = BaseNewsDataInvokeCallBack()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onItemClick(index: Int, isFromAdaptor: Boolean, adapter: BaseRecyclerAdapter<*>?) {
        val item = movieGridAdapter.getItem(index)
        val type = item.getType()
        NewsItemClickUtils.OpenItemNewsHandle(context, type, item, catalogItem)
//        TikTokActivity.startActivity(requireContext(), item = {ArticleItem@33717} recyclerAdapter.data as ArrayList<ArticleItem>, index, catalogItem.catid, pageIndex, 0)

    }


    abstract inner class BaseDataInvokeCallBack<T> : DataInvokeCallBack<T> {
        override fun fault(`object`: Any) {
            if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                return
            }
            refreshLayout.finishRefresh(false)
            refreshLayout.finishLoadMore()
            //            refreshLayout.setRefreshing(false);
            pageIndex--
            if (`object` != null && movieGridAdapter != null && (movieGridAdapter.data == null
                        || movieGridAdapter.data.size == 0)
            ) {
                showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
            } else if (movieGridAdapter != null && (movieGridAdapter.data == null
                        || movieGridAdapter.data.size == 0)
            ) {
                showStateView(TYPE_NO_CONTENT, false)
            } else closeStateView()
            ViewUtils.showToast(activity, "获取数据失败") //,Snackbar.LENGTH_SHORT).show();
        }
    }

    inner class BaseNewsDataInvokeCallBack : BaseDataInvokeCallBack<ArticleListData?>() {
        override fun success(result: ArticleListData?) {
            if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                return
            }
            if (pageIndex == 1) refreshLayout.finishRefresh()
            result?.let {
                if (!result.more) refreshLayout.finishLoadMoreWithNoMoreData() else refreshLayout.finishLoadMore()
                //必须 的
                val floatData = result.orginData.optJSONObject("data")
                if (pageIndex == 1) {
                    if (FloatButtonGroup.haveFloatField(floatData)) {
                        initFloatWin(floatData)
                    } else {
                        hideFloatWin()
                    }
                }
                if (result.articleList != null) {
                    closeStateView()
                    if (pageIndex == 1) movieGridAdapter.data.clear()
                    val size: Int = movieGridAdapter.itemCount
                    movieGridAdapter.data.addAll(result.articleList)
                    LogUtil.i("result.componentItems " + result.componentItems.size)
                    movieGridAdapter.notifyDataSetChanged()
                }
            }
        }
    }

    inner class CategoryAdapter(layoutRes: Int) : BaseQuickAdapter<Any, BaseViewHolder>(layoutRes) {

        var choosePosition: Int = 0

        override fun convert(helper: BaseViewHolder, item: Any?) {
            val content: TextView = helper.getView(R.id.content)
            item?.let {
                content.text = "$it"

                if (helper.adapterPosition == choosePosition) {
                    content.backgroundResource = R.drawable.shape_f4f4f4_corner_4_bg
                    content.textColor = Color.parseColor("#FD4E03")
                } else {
                    content.backgroundResource = 0
                    content.textColor = Color.parseColor("#333333")
                }
            }

            helper.itemView.setOnClickListener {
                if (isFastClick()) {
                    chooseType = true
                    choosePosition = helper.adapterPosition
                    refresh()
                    notifyDataSetChanged()
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        compositeDisposable.dispose()
        if (dataInvoker != null) {
            dataInvoker!!.destory()
        }
    }

    override fun f5() {
        recyclerView.scrollToPosition(0)
        refreshLayout.autoRefresh(200)
    }

    override fun gun() {

    }
}